<?php
class ZWeixin
{
	//主入口（判断消息类型）
	static public function Run($user, $msgType, $postObj, $event = '') {
		switch($msgType){
			case 'event':
				return self::Event($user, $postObj, $event);
				break;
			case 'text':
				return self::Text($user, $postObj);
				break;
			default:
				return self::Text($user, $postObj);
		}
	}
	
	
	//Event事件类型，subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
	static public function Event($user, $postObj, $event){
		//订阅（关注）
		$fromUserName = strval($postObj->FromUserName);
		$toUsername = strval($postObj->ToUserName);
		$createTime = intval($postObj->CreateTime);
		if($event == 'subscribe'){
			$client = Table::Fetch('client', $fromUserName, 'openid');
			if($client){
				Table::UpdateCache('client', $client['id'], array(
					'is_delete' => 0,
				));
			}else{
				DB::Insert('client', array(
					'openid' => $fromUserName,
					'create_time' => $createTime,
					'user_id' => $user['id'],
				));
			}
			//欢迎语
			if($user['welcome_text'] != ''){
				$content = $user['welcome_text'];
				$content = str_replace('\n\r', '@@@', $content);
				$content = explode("@@@", $content);
				$content = implode("\n\r", $content);
				$response = "<xml>
					<ToUserName><![CDATA[" . $fromUserName . "]]></ToUserName>
					<FromUserName><![CDATA[" . $toUsername . "]]></FromUserName>
					<CreateTime>" . time() . "</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[" . $content . "]]></Content>
					<FuncFlag>0</FuncFlag>
				</xml>";
				return $response;
			}
		}
		//取消订阅（关注）
		elseif($event == 'unsubscribe'){
			$client = Table::Fetch('client', $fromUserName, 'openid');
			Table::UpdateCache('client', $client['id'], array(
				'is_delete' => 1,
			));
		}
	}
	
	//文本消息
	static public function Text($user, $postObj){
		$fromUserName = strval($postObj->FromUserName);
		$toUsername = strval($postObj->ToUserName);
		$ask = strval($postObj->Content); //用户发送的消息
		$answer = "暂未开启机器人模式，请访问<a href='http://www.yayabang.com'>yayabang.com</a>";
		$response = "<xml>
			<ToUserName><![CDATA[" . $fromUserName . "]]></ToUserName>
			<FromUserName><![CDATA[" . $toUsername . "]]></FromUserName>
			<CreateTime>" . time() . "</CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[" . $answer . "]]></Content>
			<FuncFlag>0</FuncFlag>
		</xml>";
		return $response;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	//初次验证接入
	static public function Verify($verify) {
		$tmpArr = array($verify['token'], $verify['timestamp'], $verify['nonce']);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $_GET["signature"] ){
			return true;
		}else{
			return false;
		}
	}
}















?>
